package com.ddwl.message.service;

import com.ddwl.common.exception.CommonException;
import com.ddwl.common.exception.ExceptionCode;
import com.ddwl.common.util.ObjectUtil;
import com.ddwl.message.mapper.MessageMapper;
import com.ddwl.message.mapper.MessageUserMapperOld;
import com.ddwl.message.model.Message;
import com.ddwl.message.model.MessageUserOld;
import com.ddwl.schema.bo.base.PageBo;
import com.ddwl.schema.bo.message.MessageSearchBo;
import com.ddwl.schema.vo.message.MessageVo;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Fu Zhaohui
 * @version 1.0.0
 * @date 2019/8/13 18:08
 */
@Service
public class MessageService {

    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private MessageUserMapperOld messageUserMapper;

    public MessageVo detail(String id) {
        Message entity = messageMapper.findByPk(id);
        if (entity == null) {
            throw new CommonException(ExceptionCode.DATA_NOT_EXISTS);
        }
        MessageVo vo = new MessageVo();
        BeanUtils.copyProperties(entity, vo);
        return vo;
    }

    @Transactional(rollbackFor = Throwable.class)
    public void delete(String id, String userId) {
        messageUserMapper.delete(id, userId);
    }

    public List<MessageVo> index(PageBo<MessageSearchBo> pageBo) {
        PageHelper.startPage(pageBo.getPage(), pageBo.getPageSize()).count(false);
        List<Message> entities = messageMapper.findAll(pageBo.getParam());
        if (entities.isEmpty()) {
            return new ArrayList<>(0);
        }
        List<String> msgIds = entities.stream().map(Message::getId).collect(Collectors.toList());
        List<MessageUserOld> messageUsers = messageUserMapper.findByMsgIds(pageBo.getParam().getUserId(), msgIds);
        List<String> readMsgIds = messageUsers.stream().map(MessageUserOld::getMsgId).collect(Collectors.toList());
        return entities.stream().map(entity -> {
            MessageVo vo = new MessageVo();
            BeanUtils.copyProperties(entity, vo);
            if (readMsgIds.contains(entity.getId())) {
                vo.setRead(true);
            } else {
                vo.setRead(false);
            }
            return vo;
        }).collect(Collectors.toList());
    }
}
